<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>
  <button class="get">get请求</button>
  <button class="post">post请求</button>
  <button class="getinfo">ajax获取用户信息</button>
  <script>
    $(function() {
      let token = ''
      // get
      $('.get').click(function() {
        $.ajax({
          type: 'GET',
          url: 'http://127.0.0.1/api/get',
          success: (res) => {
            console.log(res)
            token = res.token
          }
        })
      })
      // ajax获取用户信息
      $('.getinfo').click(function() {
        $.ajax({
          type: 'GET',
          url: 'http://127.0.0.1/admin/getinfo',
          beforeSend: function(xhr) {
            // console.log("Bearer " + token)
            xhr.setRequestHeader("Authorization", "Bearer " + token)
          },
          // headers: 
          success: (res) => {
            console.log(res)
          }
        })
      })
      // post
      $('.post').click(function() {
        // let userInfo = {name: 'zs', age: 10}
        // let data = JSON.stringify(userInfo)
        $.ajax({
          type: 'POST',
          url: 'http://127.0.0.1/api/post',
          data: {name: 'zs', age: 10},
          success: (res) => {
            console.log(res)
          }
        })
      })
    })
  </script>
</body>
</html>